#!/bin/bash

function pack_img {
	if [ -d "${1}" ] && [ -d "unpack_${1}" ] ; then
		echo "****** Packing ${1}/ to ${1}.img-raw"
		mkbootfs ${1} | gzip > unpack_${1}/initrd.img-new

		echo "****** Creating ${1}.img"
		rm -f target_img/${1}.img
		if [ -f unpack_${1}/zImage ] ; then
			echo ">> Kernel is included in ${1}.img"
			abootimg --create target_img/${1}.img -f unpack_${1}/bootimg.cfg -k unpack_${1}/zImage -r unpack_${1}/initrd.img-new
		else
			echo ">> Kernel is NOT included in ${1}.img"
			rkcrc -k unpack_${1}/initrd.img-new target_img/${1}.img
		fi

		echo ""
		echo ""
	else
		echo "Error. Folder $1/ doesn't exist!"
		exit 1
	fi
}

if [ ! -d unpack_boot ] && [ ! -d unpack_recovery ] ; then
	echo "You have to run ${0} in the folder containing unpack_boot, boot and/or unpack_recovery, recovery folders."
	exit 1
fi
if [ ! -n "${1}" ] ; then
	echo "Usage: ${0} [boot] [recovery]"
	exit 0
fi

# create output directory
mkdir -p target_img >/dev/null 2>&1 || true

pack_img ${1}
if [ -n "${2}" ] ; then
	pack_img ${2}
fi
